package jwlee.testthread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PipedReader;
import java.io.PipedWriter;

public class ThreadCommunication {
	public void communicationByBytes() {
		try {
			final PipedOutputStream pos = new PipedOutputStream();
			final PipedInputStream pis = new PipedInputStream(pos);
			new Thread("pos thread") {
				public void run() {
					try {
						String data = "thread communication by bytes";
						pos.write(data.getBytes());
						pos.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}.start();
			new Thread("pis thread") {
				public void run() {
					try {
						byte[] bytes = new byte[pis.available()];
						pis.read(bytes, 0, bytes.length);
						System.out.println(Thread.currentThread().getName()
								+ " : " + new String(bytes));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void communicationByChars() {
		try {
			PipedWriter pw = new PipedWriter();
			PipedReader pr = new PipedReader(pw);
			final BufferedWriter bw = new BufferedWriter(pw);
			final BufferedReader br = new BufferedReader(pr);
			new Thread("pw thread") {
				public void run() {
					try {
						String data = "thread communication by characters";
						bw.write(data, 0, data.length());
						bw.newLine();
						bw.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}.start();
			new Thread("pw thread") {
				public void run() {
					try {
						System.out.println(Thread.currentThread().getName()
								+ " : " + br.readLine());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		ThreadCommunication tc = new ThreadCommunication();
		tc.communicationByBytes();
		tc.communicationByChars();
	}
}
